package com.example.conusmer.exception

import com.example.common.exception.DemoException
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.context.request.WebRequest
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException

@ControllerAdvice
class GlobalExceptionHandler {
    val logger = LoggerFactory.getLogger("GlobalExceptionHandler")

    @ExceptionHandler(DemoException::class)
    fun handleCustomerNotFoundException(ex: DemoException, request: WebRequest): ResponseEntity<Map<String, Any>> {
        logger.error("CustomerException occurred: ${ex.message}", ex)
        val msg =ex.message ?: "业务异常"
        val response = mapOf(
            "code" to "-2",
            "msg" to msg,
        )
        return ResponseEntity(response, HttpStatus.NOT_FOUND)
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException::class)
    fun handleMethodArgumentTypeMismatchException(ex: MethodArgumentTypeMismatchException, request: WebRequest): ResponseEntity<Map<String, Any>> {
        logger.error("MethodArgumentTypeMismatchException occurred: ${ex.message}", ex)
        val response = mapOf(
            "code" to "-3",
            "msg" to "请求参数非法",
        )
        return ResponseEntity(response, HttpStatus.NOT_FOUND)
    }
    @ExceptionHandler(Exception::class)
    fun handleGlobalException(ex: Exception, request: WebRequest): ResponseEntity<Map<String, Any>> {
        logger.error("Global exception occurred: ${ex.message}", ex)
        val response = mapOf(
            "code" to "-1",
            "msg" to "系统异常",
        )
        return ResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR)
    }
}
